<?php
// +----------------------------------------------------------------------
// | INPHP
// | Copyright (c) 2023 https://inphp.cc All rights reserved.
// | Licensed ( https://opensource.org/licenses/MIT )
// | Author: 幺月儿(https://gitee.com/lulanyin) Email: inphp@qq.com
// +----------------------------------------------------------------------
// | 字符串处理
// +----------------------------------------------------------------------
namespace Inphp\Core\Util;

class Str
{
    /**
     * 空格全部去掉
     * @param string $string
     * @param string $replace
     * @return string
     */
    public static function trim(string $string, string $replace = ""): string
    {
        return !empty($string) ? preg_replace("/\s+/", $replace, $string) : "";
    }

    /**
     * 删除开头字符(如果存在)
     * @param string $string
     * @param string|array $prefix
     * @return string
     */
    public static function deletePrefix(string $string, string|array $prefix): string
    {
        $prefix = is_array($prefix) ? $prefix : [$prefix];
        foreach ($prefix as $pre) {
            $string = mb_stripos($string, $pre) === 0 ? mb_substr($string, mb_strlen($pre)) : $string;
        }
        return $string;
    }

    /**
     * 随机字符
     * @param int $len
     * @return string
     */
    public static function randomString(int $len = 6): string
    {
        $strings = str_split("abcdefghijklmnpqrstuvwxyz1234567890");
        $stringsLen = count($strings) - 1;
        $str = [];
        for ($i = 0; $i < $len; $i++) {
            $str[] = $strings[mt_rand(0, $stringsLen)];
        }
        return join("", $str);
    }

    /**
     * 随机字符
     * @param int $len
     * @return string
     */
    public static function randomNumber(int $len = 6): string
    {
        $strings = str_split("0123456789");
        $stringsLen = count($strings) - 1;
        $str = [];
        for ($i = 0; $i < $len; $i++) {
            $str[] = $strings[mt_rand($i === 0 ? 1 : 0, $stringsLen)];
        }
        return join("", $str);
    }

    /**
     * 是否是中国的手机号码
     * @param mixed $phone
     * @param string|int $countryCode
     * @return bool
     */
    public static function isPhoneNumber(mixed $phone = null, string|int $countryCode = 86) : bool
    {
        if (empty($phone) || !is_numeric($phone)) {
            return false;
        }
        $countryCode = stripos($countryCode, "+") === 0 ? substr($countryCode, 1) : $countryCode;
        $countryCode = is_numeric($countryCode) && $countryCode >= 0 ? $countryCode : 86;
        //先处理中国号码，其它的都可以通过！！！
        return $countryCode !== 86 || preg_match("/^1[3|4|5|6|7|8|9]{1}[0-9]{9}$/", $phone) > 0;
    }

    /**
     * 检测是否属于字母开头、中间可插入下划线，字母或数字结尾
     * @param string|null $string
     * @return bool
     */
    public static function isLUN(?string $string): bool
    {
        return !empty($string) && preg_match("/^[a-z0-9][a-z0-9_]*[a-z0-9]$/i", $string) > 0;
    }
}